package com.briup.day19;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @author ThinkBook
 */
public class Test01_Set {
    //使用hashset添加自定义student对象
    public static void main(String[] args) {
        Student s1 = new Student("zs",20);
        Student s2 = new Student("zs",20);
        Student s3 = new Student("ls",21);
        Student s4 = new Student("ww",19);
        Student s5 = new Student("zl",22);

        Set<Student> set = new HashSet<>();
        //2.添加自定义对象
        boolean f = set.add(s1);
        System.out.println("add zs 20: " + f);
        f = set.add(s2);
        System.out.println("add zs 20: " + f);

        set.add(s3);
        set.add(s4);
        set.add(s5);

        //3.遍历
        for (Student s : set) {
            System.out.println(s);
        }

    }
    //set集合的特点测试
    public static void main01(String[] args) {
        //1.set引用指向实现类对象
        Set<String> set = new HashSet<>();

        //2.添加元素
        set.add("hello");
        set.add("123");
        set.add("nihao");
        set.add("nihao");//重复元素不会添加
        set.add("world");
        //hashSet可以包含null值
        boolean f =set.add("nihao");
        System.out.println(f);
         f =set.add(null);
        System.out.println(f);
        set.add(null);
        set.add(null);
        //3.遍历
        Iterator<String> it = set.iterator();
        while(it.hasNext()) {
            System.out.print(it.next() + "  ");
        }
        System.out.println();
    }
}
class Student{
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        System.out.println("equals");
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Student student = (Student) o;

        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;
    }

    @Override
    public int hashCode() {
        System.out.println("hashCode");
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age;
        return result;
    }
}

